package leetcode.segmentTree.p307;

/**
 * 
 * @Title: NumArray.java 
 * @Package leetcode.segmentTree.p307 
 * @Description: 307. 区域和检索 - 数组可修改
 *                  计算数组的前n项和，保存到一个数组中，
 *                  然后返回前j项和减去前i-1项和
 * @author CandyWall   
 * @date 2021年1月10日 下午2:34:19 
 * @version V1.0
 */
public class NumArray_v1 {
    private int[] sums; // sums[i]存储前i个元素的和， sum[0] = 0，
                        // sums[i]存储nums[0...i-1]
    private int[] nums;
    public NumArray_v1(int[] nums) {
        this.nums = nums;
        sums = new int[nums.length + 1];
        for(int i = 1; i < sums.length; i++) {
            sums[i] = sums[i - 1] + nums[i - 1];
        }
    }
    
    public void update(int i, int val) {
        nums[i] = val;
        for(int k = i + 1; k < sums.length; k++) {
            sums[k] = sums[k - 1] + nums[k - 1];
        }
    }
    
    public int sumRange(int i, int j) {
        return sums[j + 1] - sums[i];
    }
    
    public static void main(String[] args) {
        int[] nums = {-2, 0, 3, -5, 2, -1};
        NumArray_v1 obj = new NumArray_v1(nums);
        System.out.println(obj.sumRange(2, 5));
        obj.update(2, 4);
        System.out.println(obj.sumRange(2, 5));
    }
}